<?php
namespace Modules\Order\Entities;

use Modules\Core\Entities\BaseEntity as Model;
use Modules\Order\Entities\ProductOrder as Order;
use ThrowException;

class UnionOrder extends Model
{
    protected $table = 'union_orders';

    static public $resourceName = '订单';

    public $ordersTemp = [];
    public $isNeedAddress = false;

    protected $guarded = [];

    public function orders()
    {
        return $this->hasMany('Modules\Order\Entities\ProductOrder', 'union_order_id');
    }

    // public function payment_record()
    // {
    //     return $this->hasOne('\Modules\Payment\Entities\PaymentRecord', 'union_order_id')->where('status', 2);
    // }

    public function payNumber()
    {
        return $this->number;
    }

    public function payPrice()
    {
        return $this->orders()->sum('pay_price');
    }

    public function title()
    {
        return $this->orders[0]->title();
    }

    public function generateNumber()
    {
        $number = 'U'. date('ymdHis') . $this->user_id . '0' . rand(10000, 99999);
        return $number;
    }

    static public function initWith($skuableMaps, $user, $address = null, $options = [])
    {
        $unionOrder = new UnionOrder([
            'user_id' => $user->id
        ]);

        // 拆分订单
        $orders = [];
        $list = $unionOrder->separateSkuables($skuableMaps);
        foreach ($list as $skuableMaps) {
            array_push($orders, Order::initWith($skuableMaps, $user, $address, $options));
        }

        $unionOrder->isNeedAddress = false;
        foreach ($orders as $order) {
            if ($order->isNeedAddress) {
                $unionOrder->isNeedAddress = true;
                break;
            }
        }

        $unionOrder->ordersTemp = $orders;
        
        return $unionOrder;
    }

    public function createAll()
    {
        foreach ($this->ordersTemp as $order) {
            $order->createAll();
        }

        $this->uuid = uniqid();
        $this->number = $this->generateNumber();

        $this->save();
        $this->orders()->saveMany($this->ordersTemp);
    }

  	// 分拆skus
    public function separateSkuables($skuables)
    {
        return [$skuables];
    }

    // public function isPayable()
    // {
    //     foreach ($this->orders as $order) {
    //         if (!$order->isPayable()) {
    //             return false;
    //         }
    //     }

    //     return true;
    // }

    public function completePay($option = [])
    {
        $isUnionOrderPay = true;
        foreach ($this->orders as $order) {
            $order->completePay($option, $isUnionOrderPay);
        }

        // 广播订单完成事件
        // event(new \Modules\Order\Events\UnionOrderPaidEvent($this));
    }
}
